<?php
class BaseDbService
{
	protected $dao;
	
	public function __construct()
	{
	}
	
	public function get($id)
	{
		return $this->dao->get($id);
	}
	
	public function add($data)
	{
		if(!array_key_exists('created', $data))
		{
			$data['created']	= date('Y-m-d H:i:s');
		}
		$result = $this->dao->add($data);
		return $result;
	}
	
	public function update($id,$data)
	{
		$result	= $this->dao->update($id, $data);
		return $result;
	}
	
	public function updateRows($condition, $data)
	{
		return $this->dao->updateRows($condition, $data);
	}
	
	public function del($id)
	{
		$result	= $this->dao->del($id);
		return $result;
	}
	
	public function deleteRows($condition)
	{
		$result = $this->dao->deleteRows($condition);
		return $result;
	}
	
	public function fetch($condition)
	{
		return $this->dao->fetch($condition);
	}
	
	public function count($condition)
	{
		return $this->dao->count($condition);
	}
	
	public function getList($con,$orderby,$start,$num,$fields='')
	{
		$condition	= array();
		if(!empty($con))
		{
			$expression	= array();
			$values		= array();
			foreach($con as $k=>$v)
			{
				
				if(is_numeric($v))
				{
					$expression[]	= $k.'=:'.$k;
					$values[$k]		= $v;
				}
				else
				{
					$expression[]	= $k.' like :'.$k;
					$values[$k]		= '%'.$v.'%';
				}
			}
			$condition['where']['expression']	= implode(' AND ',$expression);
			$condition['where']['value']		= $values;
		}
		
		$result['count'] 		= $this->dao->count($condition);
		if($result['count']>0)
		{
			if($num>0)
			{
				$condition['limit'] 	= $num;
			}
			if($start>=0)
			{
				$condition['offset'] 	= $start;
			}
			if($orderby=='')
			{
				$orderby 	= 'id ASC';
			}
			$condition['orderby'] 	= $orderby;
			if($fields!='')
			{
				$condition['fields']	= $fields;
			}
			
			$result['rows'] 			= $this->dao->fetchRows($condition);
		}
		else
		{
			$result['rows'] 		= false;
		}
		
		return $result;
	}
	
	public function getInSql($ids)
	{
		if(empty($ids))
		{
			return '';
		}
		foreach($ids as $k => $v)
		{
			$ids[$k]	= "'".str_replace("'","''",$v)."'";
		}
		return implode(',',$ids);
	}
}